package com.example.littleken.asynctasktext;

import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**用AsyncTack封装异步下载方法
 * 入参 String Url 下载文件地址
 * 入参 listener 状态监听器
 * 入参 String localPath 存放文件地址
 * 返回值
 * Created by littleken on 2018/4/23.
 */

public class DownloadHelper {
    public static final int DOWNLOAD_SUCCESS = 0;
    public static final int DOWNLOAD_FAIL_NOTDELETE = -1;
    public static final int DOWNLOAD_FAIL_IOE = -2;

    public static void download(String url,String localPath,onDownloadListener listener){
        downloadAsyncTask task = new downloadAsyncTask(url,localPath,listener);
        task.execute();
    }

    /**
     * String 入参
     * Integer 进度
     * Boolean 返回值
     */
    public static class downloadAsyncTask extends AsyncTask<String,Integer,Boolean> {
        String mFilePath;
        String mUrl;
        onDownloadListener mListener;

        public downloadAsyncTask(String mFilePath, String mUrl, onDownloadListener mListener) {
            this.mFilePath = mFilePath;
            this.mUrl = mUrl;
            this.mListener = mListener;
        }

        /**
         * 在异步任务前，在主线程中（开始前）
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //可操作UI
            if(mListener != null){
                mListener.onStart();
            }
        }

        /**
         * 后台跑的线程（进行中……）
         * @param params
         * @return
         */
        @Override
        protected Boolean doInBackground(String... params) {
                String apkUrl = mUrl;
                try {
                    URL url = new URL(apkUrl);
                    URLConnection urlConnection = url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    //获得了下载内容的总长度
                    int contentLength = urlConnection.getContentLength();
                    //建立本地安放地址
                    //Environment.getExternalStorageDirectory()获取手机存储路径,返回String类型
                    //mFilePath = Environment.getExternalStorageDirectory() + File.separator + "littleken.apk";
                    //对安放地址进行处理
                    File apkFile = new File(mFilePath);
                    if(apkFile.exists()){
                        boolean result = apkFile.delete();
                        if(!result){
                            if(mListener != null){
                                mListener.onFail(DOWNLOAD_FAIL_NOTDELETE,apkFile,"文件删除失败");
                            }
                            return false;
                        }
                    }

                    int downloadSize = 0;//当前下载长度
                    byte[] bytes = new byte[1024];
                    int length;
                    //输出管道
                    OutputStream outputStream = new FileOutputStream(mFilePath);
                    while((length = inputStream.read(bytes)) > -1){
                        outputStream.write(bytes,0,length);
                        downloadSize += length;//获得当下下载进度
                        publishProgress(downloadSize * 100/contentLength);//让主线程更新进度条
                    }
                    inputStream.close();
                    outputStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                    if(mListener != null){
                        mListener.onFail(DOWNLOAD_FAIL_IOE,new File(mFilePath),e.getMessage());
                    }
                    return false;
                }
            if(mListener != null){
                mListener.onSuccess(DOWNLOAD_SUCCESS,new File(mFilePath));
            }
            return true;
        }

        /**
         * 在主线程中，执行结果处理（事后）
         * @param result
         */
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
        }

        /**
         *在UI线程处理子线程进度
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //在  publishProgress();抛出的进度在这里会收到
            if(values != null && values.length > 0) {
                if(mListener != null){
                    mListener.onProgress(values[0]);
                }
            }

        }

        /**
         * 这东西没啥用
         * @param aBoolean
         */
        @Override
        protected void onCancelled(Boolean aBoolean) {
            super.onCancelled(aBoolean);
        }

        /**
         *
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

    public interface onDownloadListener{
        //下载开始
        void onStart();
        //下载成功
        void onSuccess(int code,File file);
        //下载失败
        void onFail(int code,File file,String message);
        //状态监听
        void onProgress(int progress);

        abstract class  onDownloadAdapter implements onDownloadListener{
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(int progress) {

            }
        }
    }
}
